<template>
    <div class="app-container">
      <div class="filter-container">
        <el-input v-model="listQuery.userName" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-input v-model="listQuery.operationType" placeholder="操作" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-delete" @click="handleDeleteAll">
         删除全部
        </el-button>
        <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
          {{ $t('table.export') }}
        </el-button>
      </div>
     <!--表格内容-->
     <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        empty-text="暂无数据，请添加或查询相关记录" 
      >
        <el-table-column label="ID" prop="logId" 
        sortable="custom" align="center" width="80" :class-name="getSortClass('logId')">
          <template slot-scope="{row}">
            <span>{{ row.logId }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作用户" prop="userName" 
        sortable="custom" align="center" width="80" >
          <template slot-scope="{row}">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="operationType" 
        sortable="custom" align="center" width="200" >
          <template slot-scope="{row}">
            <span>{{ row.operationType }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" prop="operationTime" 
        sortable="custom" align="center" width="200" >
          <template slot-scope="{row}">
            <span>{{ row.operationTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作描述" prop="operationDetails" 
        sortable="custom" align="center" width="250" >
          <template slot-scope="{row}">
            <span>{{ row.operationDetails }}</span>
          </template>
        </el-table-column>
        <!--表格内部按钮-->
        <el-table-column :label="$t('table.actions')" align="center" width="100" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <!-- <el-button type="primary" size="mini" @click="handleUpdate(row)">
              {{ $t('table.edit') }}
            </el-button> -->
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { findByPage, deleteLogById, deleteAllLogs} from '@/api/log'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import moment from 'moment'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          logName:undefined,
          operationType:undefined
        },
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        showReviewer: false,
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          logName: [{ required: true, message: '权限名不能为空', trigger: 'change' }]
        },
        downloadLoading: false,
      }
    },
    created() {
      this.getList();
    },
    methods: {
      getList() {
        this.listLoading = true;
          console.log("哈哈"+this.listQuery)
          findByPage(this.listQuery).then(response => {
            const dataList = response.data.list || [];
            const formattedList = dataList.map(item => {
                    item.operationTime = moment(item.operationTime).format('YYYY-MM-DD HH:mm:ss');
                    return item;
                });
            this.list = formattedList;
            console.log(response.data.list)
            this.total = response.data.total;
            console.log( response.data.list)
            this.listLoading = false;
            
           })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
     
     
      handleDelete(row) {
        deleteLogById(row.logId).then(() => {
              this.getList();
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
      },
      //删除所有
      handleDeleteAll() {
        this.$confirm('确定要删除全部日志吗？此操作不可恢复！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteAllLogs().then(() => {
            this.getList();
            this.dialogFormVisible = false; // 如果存在相关对话框，关闭它
            this.$notify({
              title: '成功',
              message: '全部日志删除成功',
              type: 'success',
              duration: 2000
            });
          }).catch((error) => {
            console.error('删除全部日志失败：', error);
            this.$message.error('删除全部日志时出现错误，请稍后再试');
          });
        }).catch(() => {
          // 用户取消操作时的逻辑，这里可以不做处理或者添加一些提示信息等
          this.$message({
            message: '已取消删除全部日志操作',
            type: 'info'
          });
        });
      },
      handleFetchPv(pv) {
        
      },
      handleDownload() {
        this.downloadLoading = true;
        // 调用获取所有日志数据的方法
        this.getAllLogs().then(allLogs => {
          const tHeader = ['编号', '用户名', '操作', '操作时间', '操作描述'];
          const filterVal = ['logId', 'userName', 'operationType', 'operationTime', 'operationDetails'];
          const data = this.formatJson(filterVal, allLogs);
          import('@/vendor/Export2Excel').then(excel => {
            excel.export_json_to_excel({
              header: tHeader,
              data,
              filename: 'table-list'
            });
            this.downloadLoading = false;
          });
        }).catch(error => {
          console.error('导出日志数据失败：', error);
          this.downloadLoading = false;
          this.$message.error('导出日志数据时出现错误，请稍后再试');
        });
      },
      getAllLogs() {
        return new Promise((resolve, reject) => {
          // 保存当前页码、每页显示数量等查询参数，后续恢复
          const currentPage = this.listQuery.page;
          const currentLimit = this.listQuery.limit;
          // 重置页码为1，每页显示数量可根据实际需求决定是否重置，这里保持不变
          this.listQuery.page = 1;
          const allLogs = [];
          const fetchData = () => {
            findByPage(this.listQuery).then(response => {
              const dataList = response.data.list || [];
              allLogs.push(...dataList);
              if (dataList.length < this.listQuery.limit) {
                // 如果获取的数据量小于每页显示数量，说明已经获取完所有数据
                this.listQuery.page = currentPage;
                this.listQuery.limit = currentLimit;
                resolve(allLogs);
              } else {
                // 否则继续获取下一页数据
                this.listQuery.page++;
                fetchData();
              }
            }).catch(reject);
          };
          fetchData();
        });
      },
      formatJson(filterVal, dataList) {
        return dataList.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j]);
          } else if (j === 'operationTime') {
            return moment(v[j]).format('YYYY-MM-DD HH:mm:ss');
          } else {
            return v[j];
          }
        }));
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
  </script>
  